﻿const cloud = require("wx-server-sdk");

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

const db = cloud.database();
const _ = db.command;

const normalizeString = value =>
  typeof value === "string" ? value.trim() : "";

const chunkArray = (array, size) => {
  const result = [];
  for (let i = 0; i < array.length; i += size) {
    result.push(array.slice(i, i + size));
  }
  return result;
};

const queryActivityInfo = async event => {
  const activityID = normalizeString(event && event.activityID);
  if (!activityID) {
    return { error: "缺少活动编号" };
  }

  const wxContext = cloud.getWXContext();
  const openID = wxContext.OPENID;

  let activityDoc;
  try {
    activityDoc = await db.collection("Activity_Information")
      .doc(activityID)
      .get();
  } catch (error) {
    return { error: "活动信息查询失败" };
  }

  if (!activityDoc || !activityDoc.data) {
    return { error: "未找到活动信息" };
  }

  const activityData = activityDoc.data;

  let publisherName = "";
  try {
    const publisherRes = await db.collection("User_Profile")
      .where({ OpenID: activityData.PublisherOpenID })
      .field({ Name: true, Nickname: true })
      .limit(1)
      .get();
    if (publisherRes.data && publisherRes.data.length > 0) {
      publisherName = publisherRes.data[0].Nickname || publisherRes.data[0].Name || "";
    }
  } catch (error) {
    publisherName = "";
  }

  const groupsRes = await db.collection("Activity_Group_Information")
    .where({ ActivityID: activityID })
    .orderBy("GroupStartTime", "asc")
    .get();
  const groups = groupsRes.data || [];
  const groupIDs = groups.map(item => item._id);

  let registrations = [];
  if (groupIDs.length > 0) {
    const batches = chunkArray(groupIDs, 100);
    for (const batch of batches) {
      const res = await db.collection("Group_Registration_Information")
        .where({ GroupID: _.in(batch) })
        .get();
      registrations = registrations.concat(res.data || []);
    }
  }

  const uniqueOpenIDs = Array.from(new Set(registrations.map(item => item.OpenID)));
  const profileMap = new Map();
  if (uniqueOpenIDs.length > 0) {
    const batches = chunkArray(uniqueOpenIDs, 100);
    for (const batch of batches) {
      const res = await db.collection("User_Profile")
        .where({ OpenID: _.in(batch) })
        .field({ OpenID: true, Nickname: true, Name: true, Avatar: true })
        .get();
      for (const profile of res.data || []) {
        profileMap.set(profile.OpenID, profile);
      }
    }
  }

  const registrationGroupIDs = registrations
    .filter(item => item.OpenID === openID)
    .map(item => item.GroupID);

  const groupList = groups.map(group => {
    const groupRegistrations = registrations.filter(item => item.GroupID === group._id);
    const registrants = groupRegistrations.map(reg => {
      const profile = profileMap.get(reg.OpenID) || {};
      return {
        openID: reg.OpenID,
        nickname: profile.Nickname || profile.Name || "",
        avatar: profile.Avatar || "",
        isCurrentUser: reg.OpenID === openID,
        isCheckedIn: !!reg.IsCheckedIn,
        isCheckedOut: !!reg.IsCheckedOut,
        checkInTime: reg.CheckInTime || null,
        checkOutTime: reg.CheckOutTime || null
      };
    });

    const currentUserRegistration = groupRegistrations.find(reg => reg.OpenID === openID);

    return {
      groupID: group._id,
      groupName: group.GroupName,
      groupStartTime: group.GroupStartTime,
      groupEndTime: group.GroupEndTime,
      groupRegistrationCount: group.GroupRegistrationCount,
      remark: group.Remark || "",
      registrants,
      groupRegisteredCount: registrants.length,
      currentUserRegistration: currentUserRegistration
        ? {
            isCheckedIn: !!currentUserRegistration.IsCheckedIn,
            isCheckedOut: !!currentUserRegistration.IsCheckedOut,
            checkInTime: currentUserRegistration.CheckInTime || null,
            checkOutTime: currentUserRegistration.CheckOutTime || null
          }
        : null
    };
  });

  return {
    activityID,
    activityName: activityData.ActivityName,
    activityLocation: activityData.ActivityLocation,
    registrationStartTime: activityData.RegistrationStartTime,
    registrationEndTime: activityData.RegistrationEndTime,
    activityDetails: activityData.ActivityDetails,
    activityImageURL: activityData.ActivityImageURL,
    activityRequirements: activityData.ActivityRequirements,
    activityStatus: activityData.Status,
    publisherOpenID: activityData.PublisherOpenID,
    publisherName,
    isRegistrant: registrationGroupIDs.length > 0,
    registrationGroupIDs,
    activityGroups: groupList
  };
};

exports.main = async (event, context) => {
  return queryActivityInfo(event, context);
};
